package com.cyw.note.service.impl;

import com.cyw.common.core.domain.R;
import com.cyw.note.dao.NoteRepository;
import com.cyw.note.entity.Note;
import com.cyw.note.service.NoteService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

/**
 * @Author: Chenyw
 * @Date: 2022/08/22/17:23
 */
@Service
public class NoteServiceImpl implements NoteService {

    @Autowired
    private NoteRepository noteRepository;

    @Override
    public R<Note> saveOrUpdateNote(Note note) {
        if (ObjectUtils.isEmpty(noteRepository.save(note))){
            return R.fail();
        }
        return R.ok(noteRepository.save(note));
    }

    @Override
    public R<Page<Note>> findAllByPage(int currentPage, int pageSize) {
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize, Sort.sort(Note.class).by(Note::getCreateTime).ascending());
        Page<Note> notePage = noteRepository.findAll(pageRequest);
        return R.ok(notePage);
    }

    @Override
    public R removeNote(String id) {
        noteRepository.deleteById(id);
        return R.ok();
    }
}
